#include <iostream>
#include <vector>
#include <set>
#include <cstdlib>

using namespace std;

static bool prime(uint64_t n) {
    if (n < 2)
        return false;
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;

    for (uint64_t i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return false;
    }

    return true;
}

static bool concatenate_prime(int a, int b) {
    int d = 10;
    while (b >= d) 
        d *= 10;
    int p1 = a * d + b;
    d = 10;
    while (a >= d)
        d *= 10;
    int p2 = b * d + a;
    return prime(p1) && prime(p2);
}

static bool join(set<int>& s, int a) {
    for (auto e : s) {
        if (!concatenate_prime(a, e))
            return false;
    }
    s.insert(a);
    if (s.size() == 5) {
        cout << "Found a set of 5: ";
        for (auto e : s) {
            cout << e << " ";
        }
        cout << endl;
        int sum = 0;
        for (auto e : s) {
            sum += e;
        }
        cout << "Sum: " << sum << endl;
        exit(0);
    }
    return true;
}

int main() {
    vector<int> primes {3, 7};
    vector<set<int>> vs {{3, 7}};
    for (int i = 11; ; i += 2) {
        if (!prime(i))
            continue;
        bool f = true;
        for (auto& s: vs) {
            f = f && join(s, i);
        }
        if (f)
            continue;
        vs.push_back({i});
        for (auto e : primes) {
            join(vs.back(), e);
        }
        primes.push_back(i);
    }
}